import cv2 as cv
import LineTrack
import time
import os
import NumDirect
import serial
# import RPi.GPIO as GPIO  # 引入函数库


def decode_fourcc(cc):
	return "".join([chr((int(cc) >> 8 * i) & 0xFF) for i in range(4)])


cap = cv.VideoCapture("./resources/002210.avi")
# GPIO.setmode(GPIO.BOARD)  # 设置引脚编号规则
# GPIO.setup(12, GPIO.OUT)  # 将12号引脚设置成输出模式
# GPIO.output(12, 1)  # 将引脚的状态设置为高电平，此时LED亮了
FPS = int(cap.get(cv.CAP_PROP_FPS))

cap.set(cv.CAP_PROP_FRAME_HEIGHT, 480)
cap.set(cv.CAP_PROP_FRAME_WIDTH, 640)
writer = cv.VideoWriter()
write_flag = False
ret, frame = cap.read()

SIZE = (frame.shape[1] // (frame.shape[0] // 480), 480)
line = LineTrack.Line(height=480, width=640)
detector = NumDirect.Director()
# ser = serial.Serial('/devttyAMA0', 115200, timeout=1)  # 打开串口
'''
photos = []
files = os.listdir('length')
for file in files:
	if file.endswith('.jpg') or file.endswith('.png'):
		photos.append('length/' + file)
ret = len(photos) - 1
'''

header = oct(56)
end = oct(25)

if __name__ == "__main__":
	while ret:
		ret, frame = cap.read()
		# frame = cv.imread(photos[ret])
		# frame = cv.resize(frame, SIZE)
		cv.imshow("win", frame)
		dis, rois = line.Track(frame.copy())

		print(dis, rois)
		detector.Direct(rois, frame)

		# ser.write(''.encode(detector.direction))
		angle = line.GetAngle()
		id = line.direction
		# ser.write('{}{}{}{}{}{}'.format(header, id, angle, dis, 0, end).encode())
		key = cv.waitKey(FPS)
		if write_flag and writer.isOpened():
			writer.write()

		if key == ord('q'):
			cv.destroyAllWindows()
			break
		elif key == ord('s'):
			picture_name = "./" + time.strftime("%H%M%S", time.localtime()) + ".jpg"
			cv.imwrite(picture_name, frame)
			print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
		elif key == ord('r'):
			video_name = "./" + time.strftime("%H%M%S", time.localtime()) + ".mp4"
			writer.open(video_name, cv.VideoWriter_fourcc(decode_fourcc(cap.get(cv.CAP_PROP_FOURCC))), FPS, SIZE)
			write_flag = True
			print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
		elif key == ord('o'):
			if writer.isOpened():
				writer.release()
			else:
				print("Not recording.")
		elif key == ord(' '):
			cv.waitKey(0)
	# cv.waitKey(0)
	# ret -= 1
cap.release()
cv.destroyAllWindows()

'''
def test():
	line = LineTrack.Line

	origin = cv.imread("144033.jpg")
	height, width, channel = origin.shape
	SIZE = (width // (height // 480), 480)
	frame = cv.resize(origin, SIZE)
	clone = frame.copy()
	cv.imshow("win", frame)
	# r_thresh = line.FindLine(clone)
	# if line.GetHorizon():
	# 	NumDirect.NumMain(frame, r_thresh)
	cv.waitKey(0)

'''
# GPIO.cleanup()  # 程序的最后别忘记清除所有资源
